package com.yhn.hxds.common.config;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.io.IOException;

public class CustomJackson2JsonRedisSerializer<T> implements RedisSerializer<T> {

    private final ObjectMapper objectMapper;

    public CustomJackson2JsonRedisSerializer() {
        objectMapper = new ObjectMapper();
        // 禁用对未找到属性抛出异常
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 设置字符集为 UTF-8
        objectMapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
    }

    @Override
    public byte[] serialize(T object) throws SerializationException {
        try {
            return objectMapper.writeValueAsBytes(object);
        } catch (IOException e) {
            throw new SerializationException("Could not write JSON: " + e.getMessage(), e);
        }
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null) {
            return null;
        }
        try {
            // 使用 TypeReference 指定具体类型
            return objectMapper.readValue(bytes, new TypeReference<T>() {});
        } catch (InvalidFormatException e) {
            throw new SerializationException("Invalid format for JSON: " + e.getMessage(), e);
        } catch (IOException e) {
            throw new SerializationException("Could not read JSON: " + e.getMessage(), e);
        }
    }
}
